import { getToken, getConn } from "@/store/user.js";

export const fetch = (
  method,
  url,
  params = {},
  data = {},
  errMsg,
  hasToken = true
) =>
  new Promise(async (resolve, reject) => {
    const that = this;
    const token = getToken();
    let header = {
      Accept: "application/json, text/plain, */*",
      "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
      "content-type": "application/json",
    };
    if (hasToken) {
      header["Token"] = token;
    }
    let arr = [];
    for (const key in params) {
      if (Object.hasOwnProperty.call(params, key)) {
        const element = params[key];
        if (element) arr.push(`${key}=${element}`);
      }
    }

    let baseUrl = "";
    // #ifdef H5
    // 如需跨域参照以下h5跨域配置
    baseUrl = "/wms";
    // #endif

    // #ifdef APP-PLUS
    baseUrl = getConn().wms;
    console.log(
      "fetch url =>",
      `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`
    );
    // #endif

    uni.request({
      method,
      url: `${baseUrl}${url}${arr.length > 0 ? "?" + arr.join("&") : ""}`,
      header,
      data,
      success(res) {
        if (res.data.code == 1 || res.data.code=='1') {
          return resolve(res.data);
        } else {
          return reject(res.data);
        }
      },
      fail(err) {
        return reject(err);
      },
      complete(res) {
        // console.log('url', url);
        // console.log('data', data);
        // console.log('res', res);
        if (res.data.code == 401) {
          uni.redirectTo({
            url: "/pages/login/index",
          });
        }
      },
    });
  }).catch((res) => {
    uni.$emit("openToast", {
      type: "error",
      icon: "error",
      title: errMsg ? errMsg : res.msg ? res.msg : "服务器异常...", //app 只能显示7个汉字
    });
    return Promise.reject({});
  });
export default fetch;
